import React from 'react'
import { connect } from 'react-redux';
import { Icon, message, Input, Row, Col, Button, Spin, Checkbox, Popover } from 'antd'
// import './bank-bill-list.scss'
import { messages, deepFullCopy } from 'share/common';
import moment from 'moment'
// import bankBillListService from './bank-bill-list.service';
import NewExpense from 'containers/my-account/new-expense';
import SlideFrame from 'components/slide-frame';
import DiDiService from './didi-expense.service';


class TransformPage extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      records: [],
      saveButtonLoading: false,
      selectedRelations: [], // 所有被选中的数据
      selectedRelationsIds: [], // 所有被选中的已拆分的Id
      selectedRecordIds: [], // 所有被全选的record
      selectedOriTotal: 0,
      agentUser: '',
      showNewExpensePage: false,
      didiExpenseInfo: [],
      selectedRowKeys: [],
      selectedTotal: 0, // 入账币种的被选中的总金额
      isAll: false, //全选
    }
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props, '555');
    console.log(nextProps,'nextProps');

    if (nextProps.records || [].length > 0) {
      let selectedRecordIds = deepFullCopy(this.state.selectedRecordIds)
      let selectedRelationsIds = deepFullCopy(this.state.selectedRelationsIds)
      let selectedRelations = deepFullCopy(this.state.selectedRelations)
      let selectedTotal = 0
      let temp = deepFullCopy(nextProps.records).map((record) => {
        let obj = {}
        let selectedRelationList = []
        obj.amount = record.companyRealPay
        obj.id = record.id
        obj.atlBankTransactionId = record.orderId
        record.notAssociated = obj
        record.selectedRelationList = selectedRelationList || []
        return record
      })
      this.setState({
        records: temp,
        selectedRecordIds,
        selectedRelationsIds,
        selectedRelations,
        selectedTotal,
      })
    }

  }



  handleOnClose = () => {
    console.log(this.state.selectedRelationsIds,'------');
    this.setState({
      selectedRecordIds: [],
      selectedRelations: [],
      selectedRelationsIds: [],
      selectedTotal: 0,
      selectedOriTotal: 0,
      selectedRowKeys: [],
      isAll : false,
    }, () => {
      this.props.hideSlide('transform')
    })
    console.log(this.state.selectedRelationsIds,'------');

  }

 /**
   * 当复选框发生变化时触发
   * @param {Object} e
   * @param {Object} record
   */
//  handleOnCheckboxChange = (e, record) => {
//   let selectedRecordIds = deepFullCopy(this.state.selectedRecordIds)
//   let selectedRelations = deepFullCopy(this.state.selectedRelations)
//   let records = deepFullCopy(this.state.records)
//   if (e.target.checked) {
//     let recordIndex = -1
//     const allSelectedRecords = records.map((recordItem, index) => {
//       if (recordItem.id === record.id) {
//         recordIndex = index
//       }
//       return recordItem
//     })
//     console.log(3333333333);
//     if (recordIndex !== -1 && allSelectedRecords[recordIndex].length > 0) {
//       selectedRecordIds.push(record.id)
//     }
//     let existFlag = false
//     this.state.selectedRelations.some((relation) => {
//       if (relation.id === record.id) {
//         existFlag = true
//         return true
//       }
//     })
//     if (!existFlag) {
//       selectedRelations.push(record)
//     }
//     let selectedOriTotal = (selectedRelations && selectedRelations.length > 0) ? selectedRelations.map((relation) => relation.actualPrice).reduce((total, num) => total + num) : 0
//     let selectedRelationsIds = selectedRelations.map(item => record.id)
//     console.log(selectedRecordIds, 'selectedRecordIds');
//     console.log(selectedRelations,'selectedRelations');
//     this.setState({
//       selectedRecordIds,
//       records: allSelectedRecords,
//       selectedRelations,
//       selectedRelationsIds,
//       selectedOriTotal,
//     })
//   } else {
//     let selectedRecordIds = deepFullCopy(this.state.selectedRecordIds)
//     if (selectedRecordIds.includes(record.id)) {
//       selectedRecordIds.splice(selectedRecordIds.indexOf(record.id), 1)
//     }
//     const allSelectedRecords = records.map((recordItem, recordIndex) => {
//       if (recordItem.id === record.id) {
//         records.splice(recordIndex, 1)
//         return true
//       }
//       return recordItem
//     })
//     let existFlag = false
//     let position = null
//     this.state.selectedRelations.some((relation, index) => {
//       if (relation.id === record.id) {
//         existFlag = true
//         position = index
//         return true
//       }
//     })
//     if (existFlag) {
//       this.state.selectedRelations.splice(position,1)
//     }
//     let resultRelations = this.state.selectedRelations
//     console.log(resultRelations,'resultRelations');
//     let resultRelationsIds = resultRelations.map((item) => record.id)
//     let selectedOriTotal = (resultRelations && resultRelations.length > 0) ? resultRelations.map((relation) => relation.actualPrice).reduce((total, num) => total + num) : 0
//     console.log(selectedOriTotal,'selectedOriTotal');
//     this.setState({
//       selectedRecordIds,
//       // records: allSelectedRecords,
//       selectedRelations: resultRelations,
//       selectedRelationsIds: resultRelationsIds,
//       selectedOriTotal
//     })
//   }
//   }

   /**
   * 金额被勾选触发
   */
   handleOnCheckboxChange = (e, line, record) => {

    console.log('e.target.checked', e.target.checked)
    console.log('line', line)
    let selectedRelations = deepFullCopy(this.state.selectedRelations)
    let selectedRelationsIds = deepFullCopy(this.state.selectedRelationsIds)
    let records = deepFullCopy(this.state.records)
    let allSelectedRecords = []
    if (e.target.checked) {
      if (!selectedRelationsIds.includes(line.id)) {
        selectedRelationsIds.push(line.id)
        selectedRelations.push(line)
      }
      allSelectedRecords = records.map((recordItem) => {
        if (recordItem.id === record.id) {
          recordItem.selectedRelationList.push(line)
        }
        return recordItem
      })
    } else {
      if (selectedRelationsIds.includes(line.id)) {
        selectedRelationsIds.splice(selectedRelationsIds.indexOf(line.id), 1)
        selectedRelations.some((relation, index) => {
          if (relation.id === line.id) {
            selectedRelations.splice(index, 1)
          }
        })
        allSelectedRecords = records.map((recordItem) => {
          if (recordItem.id === record.id) {
            recordItem.selectedRelationList.map((relationItem, relationIndex) => {
              if (relationItem.id === line.id) {
                recordItem.selectedRelationList.splice(relationIndex, 1)
              }
            })
          }
          return recordItem
        })
      }
    }
    let resultRelations = selectedRelations.filter((item) => item)
    let selectedTotal = (resultRelations && resultRelations.length > 0) ? resultRelations.map((relation) => relation.amount).reduce((total, num) => total + num) : 0
    this.setState({
      records: allSelectedRecords,
      selectedRelations: resultRelations,
      selectedRelationsIds,
      selectedTotal,
    })
  }



  /**
   * 格式化数字
   * @param {Number} nStr 数字
   */
  addCommas = (nStr) => {
    nStr = nStr + '';
    let x = nStr.split('.');
    let x1 = x[0];
    let x2 = x.length > 1 ? '.' + x[1] : '';
    let rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
  }

  /**
   * 全选或全不选
   */
  handleOnSelectedAll = (e, record) => {
    const { selectedRelations } = this.state
    let selectTotal = 0
    selectTotal += this.addCommas(Number(record.companyRealPay).toFixed(2))
    this.setState({
      selectedRelations: selectTotal
    })
  }




  handleOnTransform = async () => {
    const selectedRowKeys = this.state.selectedRelations.map(item => {
      return item.atlBankTransactionId
    })
    if (!this.state.selectedRelations || this.state.selectedRelations.length === 0) {
      message.error('请先选择滴滴消费明细')
      return false
    }
    console.log(selectedRowKeys,'selectedRowKeys');
      const didiRes = await DiDiService.getRecordsByIds(selectedRowKeys);
    if (didiRes.status === 200) {
      if ((didiRes.data || []).length !== selectedRowKeys.length) {
        message.error('存在滴滴消费记录获取消费记录详情失败，无法生成费用');
        return false;
      }
      // this.props.params.transForm()
      console.log(didiRes,'44444');
      this.setState({
        didiExpenseInfo: didiRes.data || [],
        showNewExpensePage: true,
        selectedRowKeys:[]
      });
    }
    this.setState({isAll : false})
  }

  closeFunShow = () => {
    this.setState({
      showNewExpensePage: false,
      selectedRecordIds: [],
      selectedRelations: [],
      selectedRelationsIds: [],
      selectedTotal: 0,
      selectedOriTotal: 0,
      selectedRowKeys: [],
    }, () => {
      this.props.params.handleClose();
      this.props.params.getDiDiList();
    });
  }

  handleChangeIsAll = (value) => {
    let selectedRelations = deepFullCopy(this.state.selectedRelations)
    let selectedRelationsIds = deepFullCopy(this.state.selectedRelationsIds)
    let records = deepFullCopy(this.state.records)
    let allSelectedRecords = []
    if(value){
      records.forEach(i=>{
        let line = i.notAssociated;
        let record = i;
          if (!selectedRelationsIds.includes(line.id)) {
            selectedRelationsIds.push(line.id)
            selectedRelations.push(line)
          }
          allSelectedRecords = records.map((recordItem) => {
            if (recordItem.id === record.id) {
              recordItem.selectedRelationList.push(line)
            }
            return recordItem
          })
      })
      let resultRelations = selectedRelations.filter((item) => item)
      let selectedTotal = (resultRelations && resultRelations.length > 0) ? resultRelations.map((relation) => relation.amount).reduce((total, num) => total + num) : 0
      this.setState({
        isAll: value,
        records: allSelectedRecords,
        selectedRelations: resultRelations,
        selectedRelationsIds,
        selectedTotal,
      });
    }else{
      this.setState({
        isAll: value,
        selectedRelations: [],
        selectedRelationsIds:[],
        selectedTotal: 0,
      });
    }
  };


  render() {
    const { selectedRelationsIds,showNewExpensePage,didiExpenseInfo,selectedTotal, isAll } = this.state
    const {
      handleOnNewExpenseClose,
      slideFrameShowFlag,
      user,
      resetDiDiPage,
      agentName,
      agentOid,
      closeFun,
      didiOrderKeys
    } = this.props.params
    const records = (deepFullCopy(this.state.records) || []).sort((i,j)=> moment(i.departureTime).diff(moment(j.departureTime),'days'))

    return (
      <div>
        {records.map((record, index) => {
          return (
            <div className={'splitBlock'}>
              <div
                className={'blockHead'}
                style={{
                  height: '120px',
                  lineHeight: '30px'
                }}
              >
                <span className={'headText'}>交易日期：</span>
                <span className={'headText'}>{record.payTime ? moment(record.payTime).format('YYYY-MM-DD') : '-'}</span>
                <br />
                <span className={'headText'}>上车时间:</span>
                <span className={'headText'}>{record.departureTime ? moment(record.departureTime).format('YYYY-MM-DD') : '-'}</span>
                <span style={{ marginRight: '5px', marginLeft: '5px' }}>|</span>
                <span className={'headText'}>下车时间:</span>
                <span className={'headText'}>{record.finishTime ? moment(record.finishTime).format('YYYY-MM-DD') : '-'}</span>
                <br />
                <span className={'headText'}>上车地点:</span>
                <span className={'headText'}>{record.actualStartName}</span>
                <br />
                <div
                  style={{
                    height: '30px',
                    width: '100%',
                    overflow: 'hidden',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis',
                    marginBottom: '-30px'
                  }}
                >
                  <span className={'headText'}>下车地点:</span>
                  <span className={'headText'}>{record.actualEndName}</span>

                </div>


              </div>
              <div className={'blockContent'}>
                {record.companyRealPay ? <div className={'contentHead'}>
                  {/** 待拆分金额的checkBox */}
                  <Checkbox
                    // disabled={!record.notAssociated.amount || Number(record.notAssociated.amount) === 0}
                    checked={selectedRelationsIds.includes(record.notAssociated.id)}
                    style={{ marginRight: '10px' }}
                    onChange={(e) => this.handleOnCheckboxChange(e, record.notAssociated, record)}
                  />
                  <span className={'contentBottomText'}>{'金额'}：</span>
                  {'CNY'
                    + ' ' + this.addCommas(Number(record.companyRealPay || '0').toFixed(2))}
                </div> : null}
                </div>
            </div>
          )
        })}

        <div className="slide-footer">
          <Checkbox checked={isAll}
                    onChange={(e) => this.handleChangeIsAll(e.target.checked)}>
            {messages('request-4.key24')/*全选全部单据*/}
          </Checkbox>
          <span className={'totalText'}>总金额:</span>
          {records.length > 0 && <span style={{ color: '#FA6478', fontSize: '12px' }}>{'CNY'} </span>}
          <span style={{ color: '#FA6478' }}>{this.addCommas(selectedTotal.toFixed(2))}</span>

            <Button
              onClick={() => this.handleOnTransform()}
              loading={this.state.saveButtonLoading}
              type="primary"
              htmlType="submit"
            >
              {messages('supplier.key103')}
            </Button>
            <Button onClick={() => this.handleOnClose()}>{messages('common.cancel')}</Button>
        </div>
        <SlideFrame
          isShowCloseBtn
          slideFrameKey={'expenseTypeChooseSlideFrameKey'}
          title={'生成费用'}
          width={'800px'}
          show={showNewExpensePage}
          hasFooter={false}
          destroyOnClose={true}
          content={NewExpense}
          afterClose={this.props.params.handleOnNewExpenseClose}
          onClose={() => this.setState({ showNewExpensePage: false })}
          params={{
            didiExpenseInfo,
            didiOrderKeys,
            type: 2,
            typeProp:2,
            didiId:1,
            isDiDi:true,
            readOnly: false,
            businessCardEnabled: true,
            nowExpense: null,
            expenseSource: 'expenseType',
            slideFrameShowFlag:showNewExpensePage,
            user: user,
            hasInit: false,
            receiptOperateScene: 2,
            isCopy: false,
            resetDiDiPage: resetDiDiPage,
            agentName: agentName,
            agentOid: agentOid,
            closeFun,
            closeShow:this.closeFunShow,
            selectedTotal,
          }}
        />
      </div>
    )

  }
}

TransformPage.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    company: state.login.company,
    user: state.login.user,
    loginUser: state.login.loginUser
  };
}
export default connect(mapStateToProps)(TransformPage);
